﻿using DevExpress.Data;
using DevExpress.GridControl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DevExpress.TreeList.Pagination
{
    public partial class FormInfiniteScrolling : DevExpress.XtraEditors.XtraForm
    {
        private readonly VirtualServerModeSource virtualSource = new VirtualServerModeSource()
        {
            RowType = typeof(Person)
        };
        private readonly List<Person> persons = new List<Person>();

        public FormInfiniteScrolling()
        {
            InitializeComponent();
        }

        private void OnFormLoad(object sender, EventArgs e)
        {
            this.persons.AddRange(PersonFactory.Create(10000));
            this.maxRowCount = this.persons.Count;

            this.virtualSource.ConfigurationChanged += OnVirtualSourceConfigurationChanged;
            this.virtualSource.MoreRows += OnVirtualSourceMoreRows;

            this.gridControl1.DataSource = this.virtualSource;
        }

        private int batchSize = 50;
        private int maxRowCount = -1;

        private void OnVirtualSourceMoreRows(object sender, VirtualServerModeRowsEventArgs e)
        {
            e.RowsTask = Task.Factory.StartNew(() =>
            {
                bool moreRows = e.CurrentRowCount < this.maxRowCount - this.batchSize;
                return new VirtualServerModeRowsTaskResult(this.Query(e.CurrentRowCount), moreRows, e.UserData);
            }, e.CancellationToken);
        }

        private void OnVirtualSourceConfigurationChanged(object sender, VirtualServerModeRowsEventArgs e)
        {
            e.UserData = this.Query(0);
        }

        private List<Person> Query(int rowIndex)
        {
            return this.persons.Skip(rowIndex).Take(this.batchSize).ToList();
        }
    }
}